import {
  Component,
  ComponentFactoryResolver,
  ComponentRef,
  OnDestroy,
  OnInit,
  AfterViewInit,
  AfterContentInit,
  ViewChild,
  ViewContainerRef, AfterViewChecked, HostListener
} from "@angular/core";
import {CommService} from "../comm-service";
import {SharedService} from "../shared-service";
import {MyhttpService} from "../myhttp.service";
import {LocalStorageService} from "../local-storage-service";
import {Router} from "@angular/router";
import {FormBuilder, FormGroup} from "@angular/forms";
import {MyValidator} from "../myvalidator-util";
import {OcxhelpService} from "../ocxhelp-service";
import {sxcodeMap} from "../map-code";
import {mapMarkers, dynacomponentMap} from "../sjgzxin.zs/sjgz-basecode";
import {CompMap} from "../dynacomponent/dynamaner.component";

declare var $: any;
import * as e from "echarts";

@Component({
  template: `
    <div class="Room" [style.height]="RoomHeightstr">
      <div class="zhzs_room">
        <div class="ncdiv">
          <ng-container #zlRoom>
            <div class="dtqy">
              <div class="title">
                <div class="title_icon"></div>
                <div class="title_text">{{nowkqmc}}</div>
              </div>
              <div id="maproom"></div>
            </div>
            <div id="markerbtnRoom">
              <ul class="list-unstyled" *ngIf="markerBtns.length">
                <li class="btnitem" *ngFor="let item of markerBtns;index as i" [style.backgroundColor]="item.bg">
                <span [style.color]="item.icontext" class="btnitem-icon">
                <i [ngClass]="item.icon"></i>
                </span>
                  <span [style.color]="item.icontext" class="btnitem-name">{{item.text}}</span>
                  <span [style.color]="item.icontext" *ngIf="!item.checked" (click)="selectMaker(item)">
                  <i class="fa fa-square-o"></i>
                </span>
                  <span [style.color]="item.icontext" *ngIf="item.checked" (click)="selectMaker(item)">
                  <i class="fa fa-check-square-o"></i>
                </span>
                </li>
              </ul>
            </div>
            <div class="ctrbtn" (click)="toggleMarkBtns()">
           <span>图层  <span class="glyphicon glyphicon-chevron-up" *ngIf="btnHideflag"></span> 
             <span class="glyphicon glyphicon-chevron-down" *ngIf="!btnHideflag"></span></span>
            </div>
            <!--左上角 -天气-->
            <div class="lTroom">
              <!-- <div class="kqmc">
                <i class="fa fa-globe"></i>
                {{nowkqmc}}
              </div> -->
              <div class="orgmc">{{orgmc}}</div>
              <div class="w_tqitem">
                <div class="dicon">
                  <img style="width:100%" src="assets/img/zhzs/tq.png">
                </div>
                <div class="dlabelv_tqwd">{{w_tq}}</div>
              </div>
              <div class="w_tqitem">
                <div class="dicon">
                  <img style="width:100%" src="assets/img/zhzs/fl.png">
                </div>
                <div class="dlabel">风力</div>
                <div class="dlabelv">{{w_fl}}</div>
              </div>
              <div class="w_tqitem">
                <div class="dicon">
                  <img style="width:100%" src="assets/img/zhzs/fx.png">
                </div>
                <div class="dlabel">风向</div>
                <div class="dlabelv">{{w_fx}}</div>
              </div>
              <div class="w_tqitem">
                <div class="dicon">
                  <img style="height:100%" src="assets/img/zhzs/sd.png">
                </div>
                <div class="dlabel">湿度</div>
                <div class="dlabelv">{{w_sd}}</div>
              </div>
            </div>
          </ng-container>
        </div>
      </div>
    </div>

  `,
  styles: [
    ".Room{overflow: auto;}",
    ".zhzs_room{width: 1920px;height: 1022px;overflow: hidden;background-color:#ccc;padding:5.5px 5px;}",
    ".ncdiv{width:1910px;height:1011px;position: relative;}",
    // 中间 固定位置部分
    ".dtqy{width: 955px;height:674px; position: absolute;left: 955px;top: 0px;background-color:#fff;border:5px solid #ccc;}",
    ".dtqy>.title{position: relative;width: 100%;height: auto;padding: 10px; border-bottom: 1px solid #ccc; color: rgb(138 143 151);}",
    ".title>.title_text{height: 15px;line-height: 15px;font-size: 15px;  width: auto;border-left: 5px solid #1477F3;padding-left: 10px}",
    "#maproom{width: 945px;height:628px;}",
    // 图层控制
    ".ctrbtn{position: absolute;right: calc(15px + 0px);bottom: calc(337px + 15px);width: 165px;height: 30px;text-align: center;background-color:#2196F3;cursor: pointer;color: white; }",
    ".ctrbtn>span{line-height: 30px;font-size: 16px}",
    "#markerbtnRoom{position: absolute;right:calc(15px + 0px);bottom: calc(337px + 15px + 30px);display: none}",
    "#markerbtnRoom .btnitem{margin: 10px auto;font-size: 20px}",
    ".btnbackcss{position: absolute;right: calc(0px + 480px);top: 10px;background-color: rgba(49, 252, 255, 0.3);width: 60px;height: 40px;border-radius: 50%;text-align: center;}",
    ".btnbackcss>span{line-height: 40px;font-size: 18px;cursor: pointer;color: white}",
    ".searchRoom{position: absolute;right: calc(0px + 480px);top: 60px;width: auto;height: auto;}",
    ".searchRoom>.mysicon{position: absolute;top: 0px;right: 0px;width: 42px;height: 40px;border: 1px solid #32C2C8;border-radius: 0px 15px 15px 0px; color: #ffffff;text-align: center;font-size: 20px;padding-top: 4px;cursor: pointer}",
    ".searchRoom>.sinput{position: absolute;top: 0px;right: 42px;width: 252px;height: 40px;border:1px solid #32C2C8;border-radius: 15px 0px 0px 15px; padding: 2px 5px}",
    ".searchRoom>.sinput>input{border: none;background-color: #012549;color: #ffffff;}",
    ".searchRoom>.sinput>input::-webkit-input-placeholder{color: #ffffff}",
    ".searchRoom>.sinput>input::-moz-placeholder{color: #ffffff}",
    ".searchRoom>.sinput>input::-moz-placeholder{color: #ffffff}",
    ".searchRoom>.sinput>input::-ms-input-placeholder{color: #ffffff}",
    ".scontent{position: absolute;right: 0px;top: 42px;width: 294px;height: 300px;background-color: #0B2A44;border: 1px solid #05B5FF;border-radius: 10px}",
    ".scontent>.swarntxt{width: auto;text-align: center; height: 40px;line-height: 40px;color: #ffffff;font-size: 20px;margin-top: 50px}",
    ".scontent>#overflowShow ul{list-style: none;}",
    "#overflowShow li{padding: 5px 10px;color: #00af43;font-size: 18px;cursor: pointer}",
    ".hoverclass{color: #BFC33C!important;}",
    // ".input-room{width: 100%;height: 40px;border: 1px solid grey;position: relative;padding-top: 2px;padding-left: 1px}",
    // ".input-room>.myinput{width: 252px;height: 100%;}",
    // ".input-room>.myinput>input{border: none;background-color: #196990;color: #ffffff}",
    // ".input-room>.mysicon{position: absolute;top: 0px;right: 0px;width: 42px;height: 40px;border-left: 1px solid grey;color: #ffffff;text-align: center;font-size: 20px;padding-top: 4px;cursor: pointer}",
    // ".searchRoom>.scontent{width: 100%;height: 360px;border: 1px solid #196990;background-color: #196990}",
    ".btnitem-icon{display:inline-block; width: 40px;}",
    ".btnitem-name{display: inline-block;width: 100px;}",
    // 左上角的天气
    ".lTroom{position: absolute;left: calc(0px + 960px);top: 50px;width: auto;height: auto}",
    ".kqmc{padding-left: 20px;height: 50px;line-height: 50px;font-size: 18px; color: #707376}",
    ".orgmc{padding-left: 20px;height: 30px;line-height: 30px;font-size: 22px; color:#707376}",
    ".w_tqitem{padding-left: 25px;color: #707376;font-size: 20px;}",
    ".w_tqitem>.dicon{display: inline-block;width: 25px;height: 25px;line-height: 25px}",
    ".w_tqitem>.dlabelv_tqwd{display: inline-block;margin-left: 10px; width: auto;height: 25px;line-height: 25px}",
    ".w_tqitem>.dlabel{display: inline-block;margin-left:10px;width: auto;height: 25px;line-height: 25px}",
    ".w_tqitem>.dlabelv{display: inline-block;margin-left: 10px; width: auto;height: 25px;line-height: 25px}",
  ]
})
export class ZhzsComponent implements OnInit, OnDestroy {
  RoomHeightstr: string = "0px";
  btnHideflag: boolean = true;
  markerBtns: any[] = [];
  nowkqmc: string = "湖北省考区分布";
  orgmc: string = "湖北省天气";
  w_tq: string = "多云 0℃~10℃";
  w_fl: string = "≤3级";
  w_fx: string = "东南";
  w_sd: string = "69";

  oneh: number = 0;
  onew: number = 0;
  s_ksgljgid: string;
  s_ksjhbh: string;
  sysBasecode: string;
  sxCodeMapinit: any;
  userinfo: any;
  // 行政区划码（画地图json文件名）
  // 考区编码，请求业务数据需要的参数
  // 考试管理机构id， 用于获取下级的 行政区划码和考区的对应关系

  //根据行政区划码找到 请求下级对应关系的  xzbm-ksgljgid
  nowmap_children_xzbm2ksgljgid: any = {};
  // 行政区划码找到  考区编号，用来请求业务数据
  nowmap_children_xzbm2kqbh: any = {};
  nowmap_children_xzbm2kqmc: any = {};

  nowmap: any = {
    ksgljgid: "",
    xzmc: ""
  };
  stackMap: any[] = [{
    ksgljgid: "",
    xzmc: ""
  }];
  mapchart: any;
  mapOption: any;
  maproomH: number = 628;
  // 传递给子组件的搜索参数
  s_lastsearchlx: string;
  s_lastsearchparam: any = {
    kqbh: "",
    kqmc: "",
    ksjhbh: "",
    ksgljgid: ""
  };
  marker_kdarr: any[] = [];  // 考点
  marker_bmsarr: any[] = []; //保密室
  marker_gpsarr: any[] = []; // gps
  main_pz_XY: any[] = [];  // 某个预案或者，当前配置后的，主页面要用于展示的组件
  dynacomponentMapinit: any;

  /**
   * 勾选某个
   * @param btnobj
   */
  selectMaker(btnobj: any): void {
    const checked = btnobj.checked;
    const key = btnobj.key;
    if (checked) {
      btnobj.checked = false;
      if (key == "kdmarker") {
        if (this.marker_kdarr.length) {
          this.marker_kdarr.forEach((item) => {
            item.remove();
          });
        }
      } else if (key == "bmsmarker") {
        if (this.marker_bmsarr.length) {
          this.marker_bmsarr.forEach((item) => {
            item.remove();
          });
        }
      } else if (key === "gpsmarker") {
        if (this.marker_gpsarr.length) {
          this.marker_gpsarr.forEach((item) => {
            item.remove();
          });
        }
      }
    } else {
      btnobj.checked = true;
      const Amarker = ["kdmarker", "bmsmarker", "gpsmarker"];
      if (Amarker.indexOf(key) != -1) {
        this.handTcSimpeItem_bjxj(btnobj);
      }
    }
  }

  /**
   * 勾选内容的显示与否
   */
  toggleMarkBtns(): void {
    if (this.btnHideflag) {
      $("#markerbtnRoom").slideDown();
      this.btnHideflag = false;
    } else {
      $("#markerbtnRoom").slideUp();
      this.btnHideflag = true;
    }
  }

  /**
   * 用户信息
   */
  getuserinfo(): void {
    this.commService.getUserinfo((info) => {
      this.userinfo = info;
      this.s_ksgljgid = info.csid;
      this.getkqxx("init");
    });
  }

  /**
   *
   * @param {string} flag
   * init---初始化进入
   * refresh---ksgljg变化导致 ，考区变化
   */
  getkqxx(flag: string): void {
    if (!this.s_ksjhbh) {
      this.commService.myswal("warning", "缺少考试计划", "", "ts", null);
      return;
    }
    if (!this.s_ksgljgid) {
      this.commService.myswal("warning", "缺少考试管理机构信息", "", "ts", null);
      return
    }
    const url = "jczh/zbgz/cshhqkqxx";
    this.itservice.kwPtPost(url, {
      ksgljgid: this.s_ksgljgid,
      ksjhbh: this.s_ksjhbh
    }).subscribe(resp => {
      this.commService.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const cshhqkqxxList = resp.cshhqkqxxList; // 本机+ 下级
            let nowmapobj: any;  //  本机对象
            const nowmap_children: any[] = []; // 下级对象数组
            if (cshhqkqxxList && cshhqkqxxList.length) {
              if (cshhqkqxxList.length == 1) {
                // 肯定是本机，没下级
                nowmapobj = cshhqkqxxList[0];
                nowmap_children.length = 0;
              } else {
                const sjkqbh_list = cshhqkqxxList.map((item) => {
                  return item.sjkqbh;
                });
                cshhqkqxxList.forEach((item) => {
                  const kqbh = item.kqbh;
                  if (sjkqbh_list.indexOf(kqbh) != -1) {
                    nowmapobj = item;
                  } else {
                    nowmap_children.push(item);
                  }
                });
              }
              if (nowmap_children.length) {
                // 有下级机构，说明下级有上级. 保存上级的考试管理机构，用于下钻返回
                nowmap_children.forEach((item) => {
                  this.nowmap_children_xzbm2ksgljgid[item.xzbm] = item.ksgljgid;
                  this.nowmap_children_xzbm2kqbh[item.xzbm] = item.kqbh;
                  this.nowmap_children_xzbm2kqmc[item.xzbm] = item.kqmc;
                });
              } else {
                this.nowmap_children_xzbm2ksgljgid = {};
                this.nowmap_children_xzbm2kqbh = {};
                this.nowmap_children_xzbm2kqmc = {};
              }
              let kqbh: string = "", xzbm: string = "", ksgljgid: string = "", kqmc: string = "";
              if (nowmapobj) {
                kqbh = nowmapobj.kqbh;  // 请求接口使用
                xzbm = nowmapobj.xzbm; // 画地图使用
                ksgljgid = nowmapobj.ksgljgid; // 消息事件需要
                kqmc = nowmapobj.kqmc;
              }
              this.s_lastsearchlx = "pcompkqchange";
              this.s_lastsearchparam["ksgljgid"] = ksgljgid;
              this.s_lastsearchparam["kqbh"] = kqbh;
              this.s_lastsearchparam["kqmc"] = kqmc;
              this.s_lastsearchparam["ksjhbh"] = this.s_ksjhbh;
              if (flag == "init") {
                this.getMainComp();  // 加载动态组件
                this.drawMap(kqmc, xzbm, "init", ksgljgid); // 处理主页面地图
                this.showTqmsg(kqmc, xzbm);
                this.clearMymarkers(); //清除 markers和对应的数据
                this.handTcMarkers(false);//如果初始化就要显示某些图层数据了呢
              } else if (flag == "refresh") {
                this.sharedService.emitChange({
                  actiontype: "reqobjchange",
                  frompage: "zhzs",
                  paramchangelx: this.s_lastsearchlx,
                  paramchangedata: this.s_lastsearchparam
                });
                this.drawMap(this.nowmap["xzmc"], xzbm, "refresh", ksgljgid); // 处理主页面地图
                this.showTqmsg(kqmc, xzbm);
                this.clearMymarkers(); //清除 markers和对应的数据
                this.handTcMarkers(false);//如果初始化就要显示某些图层数据了呢
              }
            }
          } else {
            this.commService.myswal("warning", "无考区信息", "", "ts", null);
          }
        } else {
          this.getkqxx(flag);
        }
      });
    });
  }

  /**
   * 根据行政编码加载 json文件，加载地图。 找不到json文件说明没下级了
   * @param {string} xzbm
   * @param{string} flag
   * init---加载动态组件，动态组件用ngoninit接受参数请求数据
   * refresh-地图切换，发送通止给子组件
   */
  drawMap(xzmc: string, xzbm: string, flag: string, ksgljgid: string): void {
    if (!xzbm) {
      this.commService.myswal("warning", "无考区", "", "ts", null);
      return;
    }
    this.nowmap["ksgljgid"] = ksgljgid;
    // this.nowmap["xzmc"] = xzmc;
    this.nowmap["xzmc"] = "湖北";
    if (flag == "init") {
      this.mapchart = e.init(document.getElementById("maproom") as HTMLDivElement); // 一个mmp一个实列
      this.mapbindenvent2();
    } else {
      // 使用 mapbindenvent2() ，取消选中区划的高亮，需要
      this.mapchart.clear();
      this.mapchart = e.init(document.getElementById("maproom") as HTMLDivElement); // 一个mmp一个实列
      this.mapbindenvent2();
    }
    //const soureurl = `assets/mapdata/${this.sysBasecode}/${xzbm}.json`;
    const soureurl = `assets/mapdata/${this.sysBasecode}/${420000}.json`;
    const that = this;
    $.get(soureurl, function (itJson) {
      e.registerMap("xxname", itJson); // 还有一种是 JSON 文件，需要通过 AJAX 异步加载后手动注册
      that.mapOption = {
        color: ["#EF4F4F"], // series  items系列颜色
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return params.name + ' : ' + params.value[2];
          }
        },
        geo: {
          map: 'xxname',
          name: "", // 系列名称
          roam: false, // 鼠标滚动缩放或者平移，默认不开启（false）
          zoom: 1, // 当前视角的缩放比例，默认是 1
          layoutCenter: ["50%", "50%"],
          layoutSize: that.maproomH,
          aspectScale: 0.75,
          selectedMode: 'single', // 选中模式，表示是否支持多个选中，默认关闭，支持布尔值和字符串，字符串取值可选'single'表示单选，或者'multiple'表示多选。
          label: {
            show: true,
            color: '#eff0f1',
            fontSize: 16
          },
          itemStyle: {
            areaColor: "rgba(48, 113, 207,0.8)",
            borderWidth: 1,
            borderType: 'solid',
            borderColor: 'rgba(48, 113, 207,0.8)'
          },
          //regions: regionsColor,
          emphasis: {
            label: {
              show: true,
              color: '#eff0f1',
              fontSize: 20
            },
            itemStyle: {
              areaColor: 'rgba(0,80,195,1)',
              borderWidth: 3,
              borderType: 'solid',
              borderColor: '#DFB753'
            }
          }
        },
        series: [{
          name: "",
          type: 'effectScatter',
          effectType: "ripple", // 特效，目前只支持涟漪
          showEffectOn: 'render', // 绘制完成后显示特效
          rippleEffect: {
            brushType: 'stroke', // 波纹的绘制方式，可选 'stroke' 和 'fill'
            period: 2, // 动画周期 s
            scale: 5, // 动画中波纹的最大缩放比例
          },
          coordinateSystem: 'geo',
          geoIndex: 0,
          data: [],
          symbolSize: function (dataItem) {
            let sizenum;
            const itsize = dataItem[2];
            if (itsize <= 5) {
              sizenum = itsize * 5;
            } else {
              sizenum = 28;
            }
            return sizenum;
          }
        }]
      };
      that.mapchart.setOption(that.mapOption);
    });
  }

  /**
   * 不下钻的事件
   */
  mapbindenvent2(): void {
    const that = this;
    that.mapchart.on('click', function (params) {
      const selectmapName = params.name;  // 根据 map-code对应关系找到 下钻地图的经纬度数据，用汉字匹配的
      const click_xzbm = that.sxCodeMapinit[selectmapName]; // 点击的 行政区划码
      if (!that.nowmap_children_xzbm2ksgljgid[click_xzbm]) {
        that.commService.myswal("warning", "无下级地图", "", "ts", null);
        return
      }
      const click_ksgljgid = that.nowmap_children_xzbm2ksgljgid[click_xzbm]; // 点击的一级的  考试管理机构
      const click_kqbh = that.nowmap_children_xzbm2kqbh[click_xzbm]; // 点击的一级的   考区编号
      const click_kqmc = that.nowmap_children_xzbm2kqmc[click_xzbm]; // 点击的一级的考区名称
      // 不下钻。
      //1--通知子组件变化
      //2--天气 +  右下角的机构信息变化
      that.s_lastsearchlx = "pcompkqchange";
      that.s_lastsearchparam["ksgljgid"] = click_ksgljgid;
      that.s_ksgljgid = click_ksgljgid;
      that.s_lastsearchparam["kqbh"] = click_kqbh;
      that.s_lastsearchparam["kqmc"] = click_kqmc;
      that.s_lastsearchparam["ksjhbh"] = that.s_ksjhbh;
      that.s_lastsearchparam["ssqf"] = "shi";
      that.sharedService.emitChange({
        actiontype: "reqobjchange",
        frompage: "zhzs",
        paramchangelx: that.s_lastsearchlx,
        paramchangedata: that.s_lastsearchparam
      });
      that.showTqmsg(selectmapName, click_xzbm);
      that.clearMymarkers(); //清除 markers和对应的数据
      that.handTcMarkers(false);//如果初始化就要显示某些图层数据了呢
    });


    $("#maproom").click(function (e) {
      const $target = $(e.target);
      //点击表情选择按钮和表情选择框以外的地方 隐藏表情选择框
      // if (!$target.is('#maproom *')) {
      //   if (that.s_ksgljgid == that.userinfo.csid) {
      //     return;
      //   }
      //   that.s_ksgljgid = that.userinfo.csid;
      //   that.getkqxx("refresh"); // 请求动态组件
      // }
      const pagex = e.pageX;
      if (pagex < 1180 || pagex > 1760) {
        if (that.s_ksgljgid == that.userinfo.csid) {
          return;
        }
        that.s_ksgljgid = that.userinfo.csid;
        that.getkqxx("refresh"); // 请求动态组件
      }
    });
  }

  /**
   * 下钻的事件
   */
  mapbindenvent(): void {
    const that = this;
    that.mapchart.on('click', function (params) {
      const selectmapName = params.name;  // 根据 map-code对应关系找到 下钻地图的经纬度数据，用汉字匹配的
      const click_xzbm = that.sxCodeMapinit[selectmapName]; // 点击的 行政区划码
      if (!that.nowmap_children_xzbm2ksgljgid[click_xzbm]) {
        that.commService.myswal("warning", "无下级地图", "", "ts", null);
        return
      }
      const click_ksgljgid = that.nowmap_children_xzbm2ksgljgid[click_xzbm]; // 点击的一级的  考试管理机构
      that.stackMap.push({
        ksgljgid: that.nowmap["ksgljgid"],
        xzmc: that.nowmap["xzmc"]
      });
      that.s_ksgljgid = click_ksgljgid;
      that.getkqxx("refresh");
    });
  }

  /**
   *
   * @param {string} kqmc
   * @param {string} xzbm
   */
  showTqmsg(kqmc: string, xzbm: string): void {
    this.orgmc = `${kqmc}天气`;
    this.getWeatherByGaoDe(xzbm, (resp) => {
      if (resp.length) {
        const obj = resp[0];
        const wd = obj.weather + " " + obj.temperature + "℃"; // 天气+ 温度
        const fl = obj.windpower; // 风力
        const fx = obj.winddirection; // 风向
        const sd = obj.humidity; // 湿度
        this.w_tq = wd;
        this.w_fl = fl;
        this.w_fx = fx;
        this.w_sd = sd;
      }
    });
  }

  getWeatherByGaoDe(xzbm: any, callback: Function): void {
    const url = "https://restapi.amap.com/v3/weather/weatherInfo";
    $.get(url, {
      "city": xzbm,
      "key": "88e07dad205561a18c71a32db17fe1bc"
    }, (resp) => {
      const info = resp.info;
      if (info == "OK") {
        const lives = resp.lives;
        if (lives && lives.length) {
          callback(lives);
        } else {
          callback([])
        }
      } else {
        this.commService.myswal("warning", "获取天气失败", "", "ts", null);
      }
    });
  }

  /**
   * 清除所有的地图marker
   */
  clearMymarkers(): void {
    //考点
    if (this.marker_kdarr.length) {
      this.marker_kdarr.forEach((item) => {
        item.remove();
      });
      this.marker_kdarr.length = 0;
    }

    // 保密室
    if (this.marker_bmsarr.length) {
      this.marker_bmsarr.forEach((item) => {
        item.remove();
      });
      this.marker_bmsarr.length = 0;
    }
    //gps
    if (this.marker_gpsarr) {
      this.marker_gpsarr.forEach((item) => {
        item.remove();
      });
      this.marker_gpsarr.length = 0;
    }
  }

  /**
   * @param {boolean} isccchangeOnly
   *
   * isccchangeOnly= true,  考试场次变化导致重新请求的。（只需要请求那些受场次影响的接口）
   */
  handTcMarkers(isccchangeOnly: boolean): void {
    const checked_marker = this.markerBtns.filter((item) => {
      return item.checked
    });
    const A_marker = ["kdmarker", "bmsmarker", "gpsmarker"];
    //所有勾选的图层
    checked_marker.forEach((btnobj) => {
      const btnkey = btnobj.key;
      if (A_marker.indexOf(btnkey) != -1) {
        if (isccchangeOnly) {
          if (btnkey === "kdmarker") {
            this.handTcSimpeItem_bjxj(btnobj);
          }
        } else {
          this.handTcSimpeItem_bjxj(btnobj);
        }
      }
    });
  }

  /**
   * kdmarker
   * zhzxmarker
   * bmsmarker
   * gpsmarker
   * sfhysbmarker----
   * wxzcsbmarker----未实现
   * @param {string} btnkey
   */
  handTcSimpeItem_bjxj(btnobj: any): void {
    const btnkey = btnobj.key;
    const btnremoteurl = btnobj.remoteurl;  // 远程请求数据的地址
    const listname = btnobj.listname; // 接口返回的接受参数

    const reqobj = {};
    if (btnkey === "kdmarker") {
      reqobj["kqbh"] = this.s_lastsearchparam["kqbh"];
      reqobj["ksjhbh"] = this.s_lastsearchparam["ksjhbh"];
      reqobj["cxlx"] = 'bzhkd';
    } else if (btnkey == "bmsmarker") {
      reqobj["kqbh"] = this.s_lastsearchparam["kqbh"];
      reqobj["ksjhbh"] = this.s_lastsearchparam["ksjhbh"];
      reqobj["cxlx"] = 'bms';
    }

    this.itservice.kwPtPost(btnremoteurl, reqobj).subscribe(resp => {
      this.commService.handResponse("get", btnremoteurl, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const markerList = resp[listname];
            this.commService.warn("请求参数", reqobj, "");
            this.commService.warn("返回参数", markerList, "");
            if (markerList && markerList.length) {
              markerList.forEach((item) => {
                const $content = this.getMarkerContent(btnobj, item);
                if (btnkey == "kdmarker") {
                  this.marker_kdarr.push($content);
                } else if (btnkey == "bmsmarker") {
                  this.marker_bmsarr.push($content);
                } else if (btnkey == "gpsmarker") {
                  this.marker_gpsarr.push($content);
                }
                $("#maproom div:first-child").append($content);
              });

            }
          } else {
            this.handTcSimpeItem_bjxj(btnobj);
          }
        }
      });
    });
  }

  /**
   * 获取 A类图层的图标
   * @param {string} markerkey
   * @returns {any}
   */
  getMarkerContent(btnobj: any, markobj: any): any {
    const btnkey = btnobj.key;
    const markercolor = btnobj.markerbg; //marker颜色
    const markerjd = btnobj.markerjd;  //marker经度
    const markerwd = btnobj.markerwd;  //marker维度
    const markermc = btnobj.markermc; //marker名称
    const jdv = markobj[markerjd];
    const wdv = markobj[markerwd];
    const titlev = markobj[markermc];
    const xyarr = this.commService.convertTopixel(this.mapchart, jdv, wdv);
    const x = xyarr[0];
    const y = xyarr[1];
    const $content = $('<div style="width: 8px;height: 8px;border-radius: 4px 4px;cursor: pointer; background-color: ' + markercolor + '">');
    $content.attr("title", titlev);
    $content.attr("id", markobj.kdbzid);
    $content.css({
      position: "absolute",
      left: (x - 4) + "px",
      top: (y - 4) + "px"
    });
    $content.click((e) => {
      this.stopBubble(e);
      this.clickTcMarker(btnkey, markobj);
    });
    $content.on("mousemove", function () {
      $content.css({
        "width": "16px",
        "height": "16px",
        "border-radius": "50%",
        left: (x - 8) + "px",
        top: (y - 8) + "px"
      });
    });
    $content.on("mouseout", function () {
      $content.css({
        "width": "8px",
        "height": "8px",
        "border-radius": "50%",
        left: (x - 4) + "px",
        top: (y - 4) + "px"
      });
    });
    return $content;
  }

  stopBubble(e: any): void {
    if (e && e.stopPropagation) { //非IE
      e.stopPropagation();
    } else { //IE
      window.event.cancelBubble = true;
    }
  }

  clickTcMarker(btnkey: string, markobj: any): void {
    const that = this;
    if (btnkey == "kdmarker") {
      // 跳转
      const kdbhv = markobj.csbh;
      const kdmcv = markobj.csmc;
      const sendobj = {
        kdbh: kdbhv,
        kdmc: encodeURIComponent(kdmcv)
      };
      const aesstr = this.commService.aesString(JSON.stringify(sendobj));
      this.localStorageService.set("kdobj", aesstr);
      this.router.navigate(["/sjgzxin.zs", "zsbmskd"]);
    } else if (btnkey == "bmsmarker") {
      const sjbmsidv = markobj.csbh;
      const sjbmsmcv = markobj.csmc;
      const sendobj = {
        bmsbh: sjbmsidv,
        bmsmc: encodeURIComponent(sjbmsmcv)
      };
      const aesstr = this.commService.aesString(JSON.stringify(sendobj));
      this.localStorageService.set("bmsobj", aesstr);
      this.router.navigate(["/sjgzxin.zs", "zsbmskd"]);
    }
  }

  getMainComp(): void {
    this.main_pz_XY = [[{
      compkey: 'zhzs_sjys',
      topbl: 0,
      leftbl: 0
    }, {
      compkey: 'mainmap',
      topbl: 0,
      leftbl: 2
    }], [{
      compkey: 'zhzs_sjbsbsl',
      topbl: 1,
      leftbl: 0
    }, {
      compkey: 'mainmap',
      topbl: 1,
      leftbl: 2
    }], [{
      compkey: 'zhzs_sjbcrk',
      topbl: 2,
      leftbl: 0
    }, {
      compkey: 'zhzs_gjxx',
      topbl: 2,
      leftbl: 2
    }]];
    this.initMaincomp();
  }

  initMaincomp(): void {
    $(".zhzs_room .comp").each((index, item) => {
      this.zlRoom.remove(index);
    });
    const checkRoomEmpty = setInterval(() => {
      if ($(".zhzs_room .comp").length == 0) {
        clearInterval(checkRoomEmpty);
        this.main_pz_XY.forEach((row) => {
          row.forEach((cell) => {
            const compkey = cell.compkey;
            const topbl = Number(cell.topbl);
            const leftbl = Number(cell.leftbl);
            const maintop = topbl * this.oneh;
            const mainleft = leftbl * this.onew;
            if (compkey != "mainmap") {
              const dynacomponentF = this.cfr.resolveComponentFactory(CompMap[compkey]);
              let compexist: boolean = false;
              const dynacomp_class = compkey.toString().split("_")[1];    //组件中的class名
              $(".zhzs_room .comp").each(function (index, item) {
                if ($(item).hasClass(dynacomp_class)) {
                  compexist = true;
                }
              });
              if (!compexist) {
                const dynacompRef = this.zlRoom.createComponent(dynacomponentF) as ComponentRef<any>;
                dynacompRef.instance.o = {
                  frompage: "zhzs",
                  topv: maintop,
                  leftv: mainleft,
                  compkey: compkey,
                  compw: this.dynacomponentMapinit[compkey]["wbs"] * this.onew,
                  comph: this.dynacomponentMapinit[compkey]["hbs"] * this.oneh,
                  paramchangelx: this.s_lastsearchlx,
                  paramchangedata: this.s_lastsearchparam
                };
              }
            }
          });
        });
      }
    }, 100);
  }


  @ViewChild("zlRoom", {read: ViewContainerRef}) zlRoom: ViewContainerRef;

  constructor(private commService: CommService,
              private itservice: MyhttpService,
              private cfr: ComponentFactoryResolver,
              private localStorageService: LocalStorageService,
              private router: Router,
              private fb: FormBuilder,
              private myValidator: MyValidator,
              private sharedService: SharedService,
              private ocxservice: OcxhelpService) {

  }

  /**
   * 使用window 对象的事件
   * @param event
   */
  @HostListener("window:resize", ["$event"])
  onResize(event) {
    this.RoomHeightstr = this.commService.getViewPort().height + "px";
  }

  ngOnInit() {
    this.onew = 1910 / 4;   //480
    this.oneh = 1011 / 3;    //337
    this.s_ksjhbh = this.localStorageService.get("hksjh");
    this.getuserinfo();
    this.commService.getSysmsg2((resp) => {
      if (resp) {
        const sysBase = resp.sysBase;
        this.sysBasecode = sysBase;
        this.dynacomponentMapinit = dynacomponentMap[sysBase];
        this.sxCodeMapinit = sxcodeMap[this.sysBasecode];
        this.markerBtns = mapMarkers[this.sysBasecode];
      }
    });
    this.RoomHeightstr = this.commService.getViewPort().height + "px";
  }

  ngOnDestroy() {

  }

}
